<?php
/**
 * DouPHP小程序模块
 * Author: cuihaifeng  qq 366131726 微信同号
 * 网址：www.zbxingke.com www.0533hf.com
 */
if (!defined('IN_DOUCO_API')) {
    die('Access Denied');
}

/**
 * 获取用户资料
 */
function doPageAppbase()
{
    global $_GPC, $_W,$_MODULE;

    $code = $_GPC["code"];


    $appid = $_W['setting']['wxapp_key'];
    $appsecret = $_W['setting']['wxapp_secret'];
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $appsecret . "&js_code=" . $code . "&grant_type=authorization_code";

    $weixin = file_get_contents($url);
    $jsondecode = json_decode($weixin);
    $array = get_object_vars($jsondecode);
    $openid = $array["openid"];
    if ($openid) {

        $user = pdo_fetch("SELECT count(*) as n FROM " . tablename("wxapp_user") . " WHERE openid = :id", array(":id" => $openid));
        if ($user["n"] == 0) {
            $data = array("openid" => $openid, "createtime" => time());
            pdo_insert("wxapp_user", $data);
        }

        if($_MODULE['open']['user']){
            //检查会员是否存在
            $res = pdo_get('user_openid',array('openid'=>$openid),'user_id');
            if(!$res){
                $user = [
                    'email'=>$openid.'@wxapp.com',    //生成email，包含wxapp.com的是没有绑定的账号
                    'password'=>md5('666666'),                 //给一个默认密码
                    'nickname'=>'【小程序用户】'.$openid,
                    'add_time'=>time(),
                ];
                pdo_insert('user',$user);
                $user_id = pdo_insertid();
                pdo_insert('user_openid',array('user_id'=>$user_id,'openid'=>$openid));
            }else{
                $user_id = $res['user_id'];
            }
        }

        $res = array(
            'openid'=>$openid,
            'user_id'=>$user_id
        );

        return wxapp_result(0, "success", $res);
    } else {
        var_dump($weixin);
    }

}

/**
 * 用户信息
 */
function doPageUserupdate()
{
    global $_GPC, $_W,$_MODULE;
    $openid = $_GPC["openid"];
    $user = pdo_fetch("SELECT * FROM " . tablename("wxapp_user") . " WHERE openid = :id", array(":id" => $openid));
    $data = array("nickname" => $_GPC["nickname"], "avatar" => $_GPC["avatarUrl"], "gender" => $_GPC["gender"], "resideprovince" => $_GPC["province"], "residecity" => $_GPC["city"], "nationality" => $_GPC["country"]);

    if ($user) {
        pdo_update("wxapp_user", $data, array("openid" => $openid));
    } else {
        pdo_insert("wxapp_user", $data);
    }

    if($_MODULE['open']['user']){
        //检查会员是否存在
        $res = pdo_get('user_openid',array('openid'=>$openid),'user_id');
        if(!$res){
            $user = [
                'email'=>$openid.'@wxapp.com',    //生成email，包含wxapp.com的是没有绑定的账号
                'password'=>md5('666666'),                 //给一个默认密码
                'nickname'=>'【小程序用户】'.$_GPC["nickname"],
                'add_time'=>time(),
            ];
            pdo_insert('user',$user);
            $user_id = pdo_insertid();
            pdo_insert('user_openid',array('user_id'=>$user_id,'openid'=>$openid));
        }else{
            $user_id = $res['user_id'];
        }
        $user = get_user($user_id);
        //暂未绑定当前账号
        if(strexists($user['email'],'@wxapp.com')){
            //更新会员信息
            pdo_update('user',array('email'=>$_GPC["nickname"].'@wxapp.com','nickname'=>$_GPC["nickname"]),array('user_id'=>$user_id));
        }
    }


}


/**
 * 基本信息调用
 */
function doPageBase()
{
    global $_W,$dou,$_DISPLAY,$_LANG,$_MODULE;
    $data['name'] = $_W['setting']['wxapp_name'];
    $data['desc'] = $_W['setting']['wxapp_desc'];
    $data['base_color'] = $_W['setting']['wxapp_base_color'];
    $data['front_color'] = $_W['setting']['wxapp_front_color'];
    $data['logo'] = ROOT_URL.$_W['setting']['wxapp_logo'];

    //全屏广告
    $data['full_ad'] = $_W['setting']['wxapp_full_ad'];
    $data['full_ad_second'] = $_W['setting']['wxapp_full_ad_second'];
    //广告首先用幻灯模拟
    $data['full_ad_list'] = get_wx_show_list('full_ad');
    //幻灯片
    $data['slide'] = get_wx_show_list('wxapp');
    $data['tel'] = $_W['setting']['tel'];
    $data['tel_b'] = $_W['setting']['tel'];
    //头部样式
    $data['header_style'] = $_W['setting']['wxapp_header_style'];
    $data['header_banner'] = ROOT_URL.$_W['setting']['wxapp_header_banner'];
    $data['address'] = $_W['setting']['site_address'];
    $data['time'] = $_W['setting']['wxapp_time'];
    $data['latitude'] = $_W['setting']['wxapp_latitude'];
    $data['longitude'] = $_W['setting']['wxapp_longitude'];
    //视频
    $data['video'] = $_W['setting']['wxapp_video'];
    $data['video_banner'] = ROOT_URL.$_W['setting']['wxapp_video_banner'];

    $about = pdo_get('page',array('id'=>$_W['setting']['wxapp_about_id']));

    $data['base_color2'] = 'red';   //标题等颜色
    $data['about'] = $about;


    //首页产品新闻以及案例信息
    $data['recommend_product'] =  $dou->get_list('product', 'ALL', $_DISPLAY['home_product'], 'sort DESC');
    $data['new_product'] =  $dou->get_list('product', 'ALL', 9);

    if($_MODULE['open']['case'])
    {
        $data['recommend_case'] =  $dou->get_list('case', 'ALL', $_DISPLAY['home_case'], 'sort DESC');

    }
    $data['recommend_article'] =  $dou->get_list('article', 'ALL', $_DISPLAY['home_article'], 'sort DESC');

    //服务中心图片地址
    $data['service_banner'] = ROOT_URL.$_W['setting']['wxapp_service_banner'];

    //版权参数
    $data['copyright'] = $_LANG['copyright'];

    //底部菜单
    $data['tabbar_bg'] = $_W['setting']['wxapp_tabbar_bg'];
    $data['tabbar_tc'] = $_W['setting']['wxapp_tabbar_tc'];
    $data['tabbar'] = get_wxapp_nav('footer');

    //模块状态
    $data['module'] = $_MODULE['open'];

    return wxapp_result(0, "success", $data);
}

function doPageNav(){
    global $_W;
    $data = get_wxapp_nav('index');
    return wxapp_result(0, "success", $data);

}

function doPageSearch(){
    global $_W,$_GPC,$dou,$_LANG;
    $title = $_GPC['title'];
    $module = $_GPC['module']?$_GPC['module']:'product';
    if(!$title){
        return wxapp_result(404,'搜索关键词不存在');
    }

    switch ($module) {
        case 'product' : // 产品模块
            $name_field = 'name';
            break;
        default :
            $name_field = 'title';
    }
    $pindex = max(1, intval($_GPC["page"]));
    $psize = 5;
    $where = "WHERE {$name_field} LIKE :keyword";
    $params = array(':keyword'=>"%$title%");
    $data['num'] = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($module) . $where,$params);
    $data['page_size'] = $psize;
    $data["list"] = pdo_fetchall("SELECT * FROM " . tablename($module) .  $where . " ORDER BY sort DESC,id DESC LIMIT " . ($pindex - 1) * $psize . "," . $psize,$params);
    foreach ($data['list'] as $key=>$row){
        $cat_name = $dou->get_one("SELECT cat_name FROM " . $dou->table($module.'_category') . " WHERE cat_id = '$row[cat_id]'");
        $url = $dou->rewrite_url($module, $row['id']);
        $add_time = date("Y-m-d", $row['add_time']);
        $add_time_short = date("m-d", $row['add_time']);

        $description = $row['description'] ? $row['description'] : $dou->dou_substr($row['content'], 150);

        // 生成缩略图的文件名
        $image = explode('.', $row['image']);
        $thumb = ROOT_URL . $image[0] . '_thumb.' . $image[1];
        $price = $row['price'] > 0 ? $row['price'] : $_LANG['price_discuss'];
        $search_list[] = array (
            "id" => $row['id'],
            "cat_id" => $row['cat_id'],
            "name" => $row[$name_field],
            "title" => $row[$name_field],
            "price" => $price,
            "thumb" => $thumb,
            "cat_name" => $cat_name,
            "add_time" => $add_time,
            "add_time_short" => $add_time_short,
            "click" => $row['click'],
            "description" => $description,
            "url" => $url
        );
    }

    $data['list'] = $search_list;
    return wxapp_result(0,'success',$data);

}


/**
 * 网站栏目
 */
function doPageCatalog(){
    // 单页面列表
    foreach ($GLOBALS['dou']->get_page_nolevel() as $row) {
        $catalog[] = array (
            "name" => $row['page_name'],
            "mark" =>  $row['mark'],
            "type" => 'page',
            "id"=>$row['id']
        );
    }

    // 栏目模块
    foreach ($GLOBALS['_MODULE']['column'] as $module_id) {
        $catalog[] = array (
            "name" => $GLOBALS['_LANG'][$module_id . '_category'],
            "type" => $module_id . '_category',
            "id"=> 0
        );
        foreach ($GLOBALS['dou']->get_category_nolevel($module_id . '_category') as $row) {
            $catalog[] = array (
                "name" => $row['cat_name'],
                "mark" => '-' . $row['mark'],
                "type" => $module_id . '_category',
                "id"=> $row['cat_id']
            );
        }
    }

    // 简单模块
    foreach ($GLOBALS['_MODULE']['single'] as $module_id) {
        // 不显示的模块
        $no_show = 'plugin|mobile|link|fragment|wxapp';
        if (!in_array($module_id, explode('|', $no_show))) {
            $catalog[] = array (
                "name" => $GLOBALS['_LANG'][$module_id],
                "type" => $module_id,
                "id"=> 0
            );
        }
    }

    return wxapp_result(0,'success',$catalog);
}


/**
 * 获取幻灯片
 * @param string $type
 * @return array
 */
function get_wx_show_list($type = 'pc') {
    $result_list = pdo_getall('show',array('type'=>$type));
    foreach ($result_list as $k=>$row){
        $show_list[] = array (
            "id" => $row['id'],
            "show_name" => $row['show_name'],
            "show_link" => $row['show_link'],
            "show_img" => ROOT_URL . $row['show_img'],
            "sort" => $row['sort']
        );
    }
    return $show_list;
}


function get_wxapp_nav($type='index'){
    $result = pdo_getall('wxapp_nav',array('type'=>$type),'','','sort ASC');
    $nav_list = array();
    foreach ((array) $result as $value) {
        $nav_list[] = array(
            'name'=>$value['nav_name'],
            'module'=>$value['module'],
            'guide'=>$value['guide'],
            'image'=>ROOT_URL.$value['image'],
            'web'=>$value['web']
        );
    }
    return $nav_list;
}

